import { PlusOutlined } from '@ant-design/icons';
import {
  type ActionType,
  ModalForm,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
  ProFormSwitch,
  ProForm,
  ProCard,
  ProFormList,
  EditableProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, message, Row, Col } from 'antd';
import type { FC } from 'react';
import { useEffect, useState, useRef } from 'react';
import { addProduct, editProduct, getProduct, categoryTree } from '@/services/ant-design-pro/api';
import type { FormInstance } from 'antd';
import e from 'express';

interface CreateFormProps {
  reload?: ActionType['reload'];
  values?: any;
}

const CreateForm: FC<CreateFormProps> = (props) => {
  const { reload, values } = props;
  const [messageApi, contextHolder] = message.useMessage();
  const categoryRes = useRequest(() => categoryTree({ current: 1, pageSize: 100 }))
  const [formData, setFormData] = useState<any>({
    spec: [{}]
  });
  const [skuData, setSkuData] = useState<any[]>([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => []);
  const formRef = useRef<FormInstance>(null);
  
  const getProductInfo = async (id: number) => {
    const res = await getProduct(id);
    if (res.code !== 0) {
      messageApi.error('获取商品详情失败');
      return;
    }
    const specs = res.data.specs.map((item: any) => {
      return {
        id: item.id,
        name: item.name,
        values: item.values.map((v: any) => ({ value: v }))
      }
    })
    formRef.current?.setFieldsValue({
      ...res.data,
      specs,
      status: res.data.status === 1,
      categoryId: res.data.category.id,
    })
    const skus = res.data.skus.map((sku: any) => {
      return {
        ...sku,
        specValues: Object.entries(sku.specValues).map(([name, value]) => ({ name, value })),
        productId: sku.id,
      }
    })
    setSkuData(skus)
    setEditableRowKeys(skus.map((item: any) => item.id));
    console.log("🚀 ~ getProduct ~ res:", skus)
    
  }
  
  // 生成SKU数据
  const generateSKU = (specData: any[]) => {
    const spec = specData || [];
    if (!spec.length) {
      setSkuData([]);
      return;
    }

    // 过滤出有子属性的规格
    const validSpec = spec.filter((s: any) => s.name && s.values && s.values.length > 0);
    if (!validSpec.length) {
      setSkuData([]);
      return;
    }

    // 笛卡尔积生成SKU组合
    const result = validSpec.reduce((acc: any[], curr: any) => {
      const values = curr.values.filter((v: any) => v.value);
      if (acc.length === 0) {
        return values.map((v: any) => ({
          specValues: [{ name: curr.name, value: v.value }],
          price: undefined,
          stock: undefined,
          skuId: undefined
        }));
      }
      const newResult: any[] = [];
      acc.forEach(item => {
        values.forEach((v: any) => {
          newResult.push({
            ...item,
            specValues: [...item.specValues, { name: curr.name, value: v.value }]
          });
        });
      });
      return newResult;
    }, []);

    // 为每个SKU项添加唯一ID
    const skus = result.map((item: any, index: number) => ({
      ...item,
      id: index + 1
    }));

    setSkuData(skus);
    setEditableRowKeys(skus.map((item: any) => item.id));
  };


  const { run, loading } = useRequest(values ? editProduct : addProduct, {
    manual: true,
    onSuccess: () => {
      messageApi.success(values ? '修改成功' : '添加成功');
      reload?.();
    },
    onError: () => {
      messageApi.error(values ? '修改失败' : '添加失败');
    },
  });

  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  }

  // SKU表格列定义
  const skuColumns:any = [
    {
      title: 'SKU属性',
      dataIndex: 'specValues',
      editable: false,
      width: 200,
      render: (_: any, record: any) => {
        console.log("record", record)
        return record.specValues?.map((spec: any) => `${spec.name}-${spec.value}`).join(' ');
      }
    },
    {
      title: '价格',
      dataIndex: 'price',
      valueType: 'digit',
      width: 150,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入价格',
          },
        ],
      },
    },
    {
      title: '库存',
      dataIndex: 'stock',
      valueType: 'digit',
      width: 150,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入库存',
          },
        ],
      },
    },
    // {
    //   title: 'SKU ID',
    //   dataIndex: 'skuId',
    //   valueType: 'text',
    //   width: 150,
    // },
  ];

  return (
    <>
      {contextHolder}
      <ModalForm
        formRef={formRef}
        initialValues={formData}
        title={values ? "编辑商品" : "新建商品"}
        layout="horizontal"
        grid={true}
        {...formItemLayout}
        rowProps={{
          gutter: [16, 0],
        }}
        onOpenChange={(open) => {
          if (open) {
            setSkuData([])
            if (values?.id) {
              // 编辑时加载商品详情
              getProductInfo(values.id);
            }
          }
        }}
        trigger={
          values ? (
            <a>编辑</a>
          ) : (
            <Button type="primary" icon={<PlusOutlined />}>
              新建
            </Button>
          )
        }
        width="800px"
        modalProps={{ okButtonProps: { loading }, destroyOnHidden: true }}
        onFinish={async (value) => {
          if (values?.id) {
            value.id = values.id
          }
          value.status = value.status ? 1 : 2;
          value.specs = value.specs.map((item: any) => {
            return {
              id: item.id,
              name: item.name,
              valueList: item.values.map((v: any) => v.value)
            }
          })
          value.skus = skuData.map((sku: any) => {
            const obj: any = {}
            sku.specValues.forEach((spec: any) => {
              obj[spec.name] = spec.value;
            })
            return {
              id: sku.productId,
              specValues: obj,
              price: sku.price,
              stock: sku.stock,
            }
          })
          console.log("提交数据", value);
          // return
          await run(value as any);
          return true;
        }}
      >
         <ProForm.Group>
          <ProFormTreeSelect
            label="选择分类"
            fieldProps={{
              fieldNames: {
                label: 'name',
                value: 'id',
              },
              treeData: categoryRes.data,
            }}
            rules={[
              {
                required: true,
                message: '分类必选',
              },
            ]}
            width="md"
            name="categoryId"
            placeholder="请选择上级分类"
            colProps={{ span: 12 }}
          />

          <ProFormText
            rules={[
              {
                required: true,
                message: '商品名称必填',
              },
            ]}
            width="md"
            name="name"
            label="商品名称"
            placeholder="请输入商品名称"
            colProps={{ span: 12 }}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormTextArea label="描述" width="md" name="description" colProps={{ span: 12 }}/>
          <ProFormSwitch 
            width="md"
            name="status"
            label="状态"
            colProps={{ span: 12 }}/>
        </ProForm.Group>
        <ProCard
          title="商品属性"
          bodyStyle={{display: 'block'}}
          style={{ marginBottom: 16 }}
        >
          <ProFormList 
            name="specs"
            creatorButtonProps={{
              creatorButtonText: '新建属性',
            }}
            min={1}
            onAfterAdd={() => {
              const formValues = formRef.current?.getFieldsValue();
              generateSKU(formValues.specs);
            }}
            onAfterRemove={() => { 
              const formValues = formRef.current?.getFieldsValue();
              generateSKU(formValues.specs);
            }}
          >
              {(f, index, action) => {
                // console.log(f, index, action);
                return ( 
                  <ProCard
                    boxShadow
                    style={{ marginBottom: 16 }}>
                    <Row gutter={16}>
                      <Col span={20}>
                        <ProFormText
                            width="md"
                            name="name"
                            key="name1"
                            label={`属性 ${index + 1}`}
                            placeholder={'请输入属性名称'}
                            rules={[{ required: true, message: '属性名称必填' }]}
                            colProps={{ span: 12 }}
                            fieldProps={{
                              onBlur: () => {
                                const formValues = formRef.current?.getFieldsValue();
                                generateSKU(formValues.specs);
                              }
                            }}
                          />
                        <ProFormList 
                          name="values"
                          key="values"
                          creatorButtonProps={{
                            creatorButtonText: '添加子属性',
                          }}
                          onAfterAdd={() => {
                            const formValues = formRef.current?.getFieldsValue();
                            generateSKU(formValues.specs);
                          }}
                          onAfterRemove={() => { 
                            const formValues = formRef.current?.getFieldsValue();
                            generateSKU(formValues.specs);
                          }}
                        >
                          <ProForm.Group>
                            <ProFormText
                              width="md"
                              name="value"
                              key="value1"
                              placeholder={'请输入子属性名称'}
                              colProps={{ span: 24 }}
                              rules={[{ required: true, message: '子属性名称必填' }]}
                              fieldProps={{
                                onBlur: () => {
                                  const formValues = formRef.current?.getFieldsValue();
                                  generateSKU(formValues.specs);
                                }
                              }}
                            />
                          </ProForm.Group>
                        </ProFormList>
                      </Col>                      
                    </Row>
                  </ProCard>
                )
              }}
          </ProFormList>
        </ProCard>

        <EditableProTable<any>
          headerTitle="商品SKU"
          columns={skuColumns}
          rowKey="id"
          style={{width: '100%'}}
          value={skuData}
          onChange={(data: any) => setSkuData(data)}
          recordCreatorProps={false}
          editable={{
            type: 'multiple',
            editableKeys,
            // actionRender: (row, config, defaultDoms) => {
            //   return [defaultDoms.delete];
            // },
            onValuesChange: (record, recordList) => {
              console.log("recordList",recordList)
              setSkuData(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
        
      </ModalForm>
    </>
  );
};

export default CreateForm;